package proj2501.net_logo;

import proj2501.geo_util.VectorD2;

public class NLTurtle {
	private static int idSource;
	private int id;
	private NetLogo parent;
	private VectorD2 v;
	private double degreeOrientation;
	private double radianOrientation;
	private VectorD2 orientationVector;
	private NLColor color;
	
	public NLTurtle(NetLogo parent) {
		id = idSource++;
		this.parent = parent;
//		degreeOrientation = 360 * parent.random.nextDouble();
//		radianOrientation = Math.toRadians(degreeOrientation);
		setOrientationFromDegree(360 * parent.random.nextDouble());
		color = NLColor.getFrom14Primary();
	}
	
	@Override
	public String toString() {
		String s = "";
		s += "Turtle " + id + " at " + v + " aims " + degreeOrientation;
		return s;
	}
	
	public VectorD2 getVector() { return v; }
	public VectorD2 getOrientationVector() {
		if (orientationVector == null) {
			orientationVector = new VectorD2(Math.cos(radianOrientation), Math.sin(radianOrientation));
		}
		return orientationVector;
	}
	private void setOrientationFromDegree(double degree) {
		degreeOrientation = degree;
		radianOrientation = Math.toRadians(degreeOrientation);
		orientationVector = null;
	}
	public NLColor getColor() { return color; }
	private void checkWrapping() {
		if (parent.worldWrapsHorizontally) {
			double x = v.getX();
			if (parent.maxPxcor() + 0.5 < x) {
				x -= parent.minPxcor() - 0.5;
				x %= parent.worldWidth();
				x += parent.minPxcor() - 0.5;
				v = new VectorD2(x, v.getY());
			} else if (x <= parent.minPxcor() - 0.5) {
				x -= parent.minPxcor() - 0.5;
				x %= parent.worldWidth();
				x += parent.minPxcor() - 0.5;
				x += parent.worldWidth();
				v = new VectorD2(x, v.getY());
			}
		}
		if (parent.worldWrapsVertically) {
			double y = v.getY();
			if (parent.maxPycor() + 0.5 < y) {
				y -= parent.minPycor() - 0.5;
				y %= parent.worldHeight();
				y += parent.minPycor() - 0.5;
				v = new VectorD2(v.getX(), y);
			} else if (y <= parent.minPycor() - 0.5) {
				y -= parent.minPycor() - 0.5;
				y %= parent.worldHeight();
				y += parent.minPycor() - 0.5;
				y += parent.worldHeight();
				v = new VectorD2(v.getX(), y);
			}
		}
	}
	
	/////////////////////////
	
	public void fd(double number) { forward(number); }
	
	public void forward(double number) {
		if (0 <= number) {
			while (1 < number) {
				jump(1);
				number -= 1;
			}
			jump(number);
		} else {
			while (number < -1) {
				jump(-1);
				number += 1;
			}
			jump(number);
		}
	}
	
	public void jump(double number) {
		v = v.add(getOrientationVector().mul(number));
		checkWrapping();
	}
	
	public void right(double number) {
		setOrientationFromDegree(degreeOrientation + number);
	}
	
	public void rt(double number) { right(number); }
	
	public void setColor(NLColor color) { this.color = color; }
	public void setxy(double x, double y) {
		v = new VectorD2(x, y);
	}
}
